// ws.js
let wsInstance = null;
let messageListeners = []; // 保存所有注册的消息监听函数

/**
 * 创建全局 WebSocket 实例
 */
export function createWebSocket(userId) {
  if (!wsInstance) {
    // 建立连接
    wsInstance = new WebSocket(`ws://localhost:8080/app/ws/${userId}`);

    wsInstance.onopen = () => {
      console.log('✅ WebSocket 已连接');
    };

    wsInstance.onmessage = (event) => {
      const message = JSON.parse(event.data);
      console.log('📩 收到消息:', message);

      // 通知所有已注册的监听器
      messageListeners.forEach(cb => cb(message));
    };

    wsInstance.onclose = () => {
      console.log('❌ WebSocket 已关闭');
      wsInstance = null; // 释放对象，下次可重新创建
    };

    wsInstance.onerror = (error) => {
      console.error('⚠️ WebSocket 出现错误:', error);
    };
  }

  return wsInstance;
}

/**
 * 主动关闭 WebSocket
 */
export function closeWebSocket() {
  if (wsInstance) {
    wsInstance.close();
    wsInstance = null;
  }
}

/**
 * 注册消息监听器
 */
export function registerMessageListener(callback) {
  if (typeof callback === 'function') {
    messageListeners.push(callback);
  }
}

/**
 * 移除消息监听器
 */
export function removeMessageListener(callback) {
  messageListeners = messageListeners.filter(cb => cb !== callback);
}
